package repository

import (
	"fmt"
	"github.com/go-redis/redis"
	"io/ioutil"
	. "ircove.com/common"
	"regexp"
	"strconv"
	"strings"
	"sync"
)

var db *redis.Client
var lock sync.Locker = new(sync.Mutex)

var scripts map[string]*redis.Script = make(map[string]*redis.Script, 16)

func RegisterLua() error {
	dirname := GetCurDir() + "/app_data/lua/"
	dir_list, err := ioutil.ReadDir(dirname)
	if err != nil {
		return err
	}
	for _, v := range dir_list {

		if v.IsDir() {
			continue
		}
		filename := v.Name()
		if ".lua" != filename[len(filename)-4:] {
			continue
		}
		key := filename[0 : len(filename)-4]
		filename = dirname + "/" + v.Name()
		bytes, err := ioutil.ReadFile(filename)
		if err != nil {
			return err
		}
		data := string(bytes)
		regx, err := regexp.Compile("@\\w+")
		if err != nil {
			return err
		}
		dic := make(map[string]int, 10)
		stringarr := regx.FindAllString(data, -1)
		var i int = 1
		for _, v := range stringarr {
			if dic[v] == 0 {
				dic[v] = i
				i++
				fmt.Println(v)
			}
		}
		if len(dic) > 0 {
			for k, v := range dic {
				stemp := "KEYS[" + strconv.Itoa(v) + "]"
				data = strings.Replace(data, k, stemp, -1)
			}
		}
		script := redis.NewScript(data)
		scripts[key] = script
	}

	return nil
}

func LuaScript(filename string) *redis.Script {

	script := scripts[filename]

	if scripts == nil {

		RegisterLua()
		script = scripts[filename]
	}
	return script
}
func RedisConnection() *redis.Client {
	if db != nil {
		return db
	}
	lock.Lock()
	db := redis.NewClient(&redis.Options{
		Addr:     Conf.Read_String("redisdb.Address"),
		Password: "",                                 // no password set
		DB:       int(Conf.Read_Int64("redisdb.DB")), // use default DB
	})
	lock.Unlock()
	return db
}

//func Online(client *irc.Client) *redis.Client {
//     db:=RedisConnection()
//
//
//
//     db.HSet("gopushonlie")
//
//}
